package gr.unipi.cinema;

import java.sql.*;

import org.apache.commons.configuration.Configuration;

public class SqlConnection {
	
	public static Configuration config;
	
	private static final String serverAddressAttrName = "serverAddress";
	private static final String serverPortAttrName = "serverPort";
	private static final String userNameAttrName = "userName";
	private static final String passwordAttrName = "password";
	private static final String dbNameAttrName = "dbName";
	
	private static final String serverAddressDefault = "snf-54433.vm.okeanos.grnet.gr";
	private static final String serverPortDefault = "3306";
	private static final String userNameDefault = "root";
	private static final String passwordDefault = "pwd123";
	private static final String dbNameDefault = "cinemadb";
	
	private static String getAttribute(String attrName) {
		String res = null;
		
		String attr = "sqlConnection[@" + attrName + "]";
		
		res = config.getString(attr);
		if ((res != null) && (res.length() == 0)) {
			res = null;
		}
		
		return res;
	}
	
	public static Connection getConnection() {
		String serverAddress = serverAddressDefault;
		String serverPort = serverPortDefault;
		String userName = userNameDefault;
		String password = passwordDefault;
		String dbName = dbNameDefault;
		
		String value;
		
		if (config != null) {
			
			value = getAttribute(serverAddressAttrName);
			if (value != null) {
				serverAddress = value;
			}
			
			value = getAttribute(serverPortAttrName);
			if (value != null) {
				serverPort = value;
			}
			
			value = getAttribute(userNameAttrName);
			if (value != null) {
				userName = value;
			}
			
			value = getAttribute(passwordAttrName);
			if (value != null) {
				password = value;
			}
			
			value = getAttribute(dbNameAttrName);
			if (value != null) {
				dbName = value;
			}
		}
		
		Connection connect = null;
		try {
			// This will load the MySQL driver, each DB has its own driver
		    Class.forName("com.mysql.jdbc.Driver");
		    // Setup the connection with the DB
		    String connectionString = "jdbc:mysql://" + serverAddress + ":" + serverPort +
		    		"/" + dbName + "?" + "user=" + userName + "&password=" + password;
		    System.out.println("Using the following connection string for mysql connection: " + connectionString);
		    connect = DriverManager.getConnection(connectionString);
		}
		catch (Exception ex) {
			ex.printStackTrace();
		}
		
		return connect;

	}
}
